<template>
  <view>
    <!-- 加载中蒙版 -->
    <!--    <qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>-->
    <!-- #ifdef MP-WEIXIN -->
    <qmy-custom-navbar :title="'活动发布'"></qmy-custom-navbar>
    <!-- #endif -->
    <view :style="{paddingTop:menuObject.top + menuObject.height + 15 +'px'}" class="bottom-index">
      <view class="ping-30">
        <!-- 图片上传 -->
        <uni-file-picker ref="files" v-model="imgUrl" return-type="array" limit="6" mode="grid" file-mediatype="image"
          :sizeType="['compressed']"
          :image-styles="{width: '160rpx', height: '160rpx',border:false,background:'#f7f7f7',borderRadius:'20rpx',lineHeight:'160rpx'}">
        </uni-file-picker>
        <!-- 标题输入 -->
        <view class="input-box ali-item-cen flex-dir-row ali-item-cen flex-x-bet">
          <input confirm-type="done" placeholder-class="input-placeholder" type="text" v-model="title"
            placeholder="填写活动标题" cursor-color="#14cc60" :maxlength="23" class="w-100 fs-32 fw-600" />
          <text v-if="title" class="iconfont ic-qingchu fs-40 col-b1 mr-20 ml-20" @click="clearTitle"></text>
          <view class="fs-26 col-b1">{{ 23 - title.length }}</view>
        </view>
        <!-- 多行内容输入,用滚动视图防止内容过长 -->
        <scroll-view scroll-y class="mt-30 w-100 h-100 mp-html-box" @click="naTov('/pages/publish/noticeDetail')">
          <mp-html :content="content"></mp-html>
        </scroll-view>
      </view>
      <view class="heng"></view>
      <view class="ping-30">
        <view>
          <view class="br-20 w-100 mt-30 bac-col-f activity-box">
            <view class="w-100 flex-dir-row ali-item-cen flex-x-bet">
              <view class="fs-28 fw-600">添加标签</view>
              <view class="bor-bottom-f3 br-200 bac-col-f text-ali-c ping-0-20 26rpx" style="width: 340rpx;">
                <input type="text" v-model="searchTag" confirm-type="done"
                  placeholder-style="color:#b1b1b1;font-size:26rpx;text-align:center;" placeholder="输入标签名称查找" />
              </view>
            </view>
            <scroll-view scroll-x class="w-100 mt-30">
              <view class="flex-dir-row">
                <view class="flex-dir-row ali-item-cen mr-20 flex-shrink-0"
                  v-for="(item,index) in filteredActivityTagList" :key="index" @click="activeActivity(item.name)">
                  <view style="height: 50rpx;line-height: 50rpx;" class="br-10 flex-dir-row ali-item-cen pr-20"
                    :class="selectedActivity.includes(item.name) ? 'bac-col-00b col-f' : 'activity-item'">
                    <view class="fs-28 ml-20 text-element-1 flex-1">#{{ item.name }}</view>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
        <!-- 活动分类 -->
        <view class="ping-30-0">
          <view class="flex-dir-row flex-x-bet" @click="showActivityType">
            <view class="fs-28 fw-600">添加分类</view>
            <view class="flex-dir-row ali-item-cen">
              <view class="fs-24 col-b1">
                更多分类
              </view>
              <view class="iconfont ic-you fs-30 mt-5 col-b1"></view>
            </view>
          </view>
          <scroll-view scroll-x class="w-100 mt-30">
            <view class="flex-dir-row">
              <view class="flex-dir-row ali-item-cen mr-20 flex-shrink-0" :key="index"
                v-for="(item, index) in activityTypeList" @click="selectActivityType(item.id)">
                <view style="height: 50rpx;line-height: 50rpx;" class="br-10 flex-dir-row ali-item-cen pr-20"
                  :class="activityType == item.id ? 'bac-col-00b col-f' : 'activity-item'">
                  <view class="fs-28 ml-20 text-element-1 flex-1">{{ item.name }}</view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 活动分类弹出框 -->
        <uni-popup ref="popup" type="bottom" border-radius="20rpx 20rpx 0 0" backgroundColor="#fff">
          <view class="slanted-rectangle">
            <view class="fs-28 fw-600 mb-30">全部分类</view>
            <!-- 每行4个，多的换行，可滚动 -->
            <scroll-view scroll-y style="max-height: 60vh;">
              <view class="flex-dir-row flex-w-wrap" style="height: 100%;">
                <view class="fs-28 activity-type-item" v-for="(item, index) in activityTypeList" :key="index"
                  @click="selectActivityType(item.id)"
                  :style="{marginRight: (index + 1) % 4 === 0 ? '0' : '3%', width: '22.75%', marginBottom: '30rpx',background:activityType == item._id ? '#14cc60' : '#f7f7f7',color:activityType == item._id ? '#fff' : '#000'}">
                  <view class="text-element-1">{{ item.name }}</view>
                </view>
              </view>
            </scroll-view>
          </view>
        </uni-popup>
      </view>
      <view class="heng"></view>
      <view class="ping-0-30">
        <!-- 活动礼品选择 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen">
            <view class="fs-28 fw-600">活动礼品</view>
            <view class="flex-dir-row ali-item-cen">
              <view class="gift-selector" @click="showGiftSelector">
                <text v-if="!selectedGift" class="fs-26 col-b1 mr-20">选择活动礼品</text>
                <scroll-view v-else scroll-x class="fs-28 mr-20 text-element-1 whi-sp"
                  style="width: 300rpx;">{{ selectedGiftName }}
                </scroll-view>
                <text class="iconfont ic-you fs-32 mt-5 col-b1"></text>
              </view>
            </view>
          </view>
        </view>

        <!-- 活动礼品选择弹窗 -->
        <uni-popup ref="giftPopup" type="bottom" border-radius="20rpx 20rpx 0 0" backgroundColor="#fff">
          <view class="slanted-rectangle">
            <view class="fs-28 fw-600 mb-20">选择活动礼品</view>
            <!-- 搜索栏 -->
            <view class="gift-search mb-20">
              <view class="search-bar">
                <text class="iconfont ic-sousuo fs-40 mr-10 col-00ba31"></text>
                <input placeholder-class="search-placeholder" type="text" v-model="giftSearchKeyword"
                  placeholder="搜索商品名称" class="fs-26" />
                <text v-if="giftSearchKeyword.length" class="iconfont ic-qingchu fs-40"
                  @click="giftSearchKeyword = ''"></text>
              </view>
            </view>
            <!-- 商品列表 -->
            <scroll-view scroll-y style="height: 40vh;" class="gift-list">
              <!-- 无商品时显示空状态 -->
              <view v-if="filteredGiftList.length === 0" class="empty-gift">
                <text class="fs-28 col-b1">没有找到相关商品</text>
              </view>

              <!-- 可选择不设置礼品 -->
              <view class="gift-item" @click="selectGift('', '')">
                <view class="gift-info">
                  <view class="gift-name">不设置礼品</view>
                </view>
                <view class="gift-select" :class="{'selected': tempSelectedGift === ''}">
                  <text class="iconfont ic-gou1 fs-50" v-if="tempSelectedGift === ''"></text>
                </view>
              </view>

              <!-- 商品列表 -->
              <view class="gift-item" v-for="(item, index) in filteredGiftList" :key="index"
                @click="selectGift(item.id, item.goodsName)">
                <image class="gift-image" :src="item.mainImage" mode="aspectFill"></image>
                <view class="gift-info">
                  <view class="gift-name text-element-1">{{ item.goodsName }}</view>
                  <view class="gift-price">¥ {{ item.salePrice }}</view>
                </view>
                <view class="gift-select" :class="{'selected': tempSelectedGift === item.id}">
                  <text class="iconfont ic-gou1 fs-50" v-if="tempSelectedGift === item.id"></text>
                </view>
              </view>
            </scroll-view>

            <!-- 底部按钮 -->
            <view class="gift-popup-footer">
              <view class="cancel-btn" @click="$refs.giftPopup.close()">取消</view>
              <view class="confirm-btn" @click="confirmGiftSelection">确定</view>
            </view>
          </view>
        </uni-popup>
        <!-- 报名时间 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen" @click="showStartDate(0)">
            <view class="fs-28 fw-600">报名时间</view>
            <view class="flex-dir-row ali-item-cen">
              <view v-if="signUpSTime == '' || signUpETime == ''" class="fs-26 mr-20 col-b1">选择报名时间
              </view>
              <scroll-view v-else scroll-x class="fs-28 mr-20 text-element-1 whi-sp"
                style="width: 300rpx;">{{ signUpSTime + ' 至 ' + signUpETime }}
              </scroll-view>
              <view class="iconfont ic-you fs-32 mt-5 col-b1"></view>
            </view>
          </view>
        </view>
        <!-- 活动时间 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen" @click="showStartDate(1)">
            <view class="fs-28 fw-600">活动时间</view>
            <view class="flex-dir-row ali-item-cen">
              <view v-if="activitySTime == '' || activityETime == ''" class="fs-26 mr-20 col-b1">选择活动时间
              </view>
              <scroll-view v-else scroll-x class="fs-28 mr-20 text-element-1 whi-sp"
                style="width: 300rpx;">{{ activitySTime + ' 至 ' + activityETime }}
              </scroll-view>
              <view class="iconfont ic-you fs-32 mt-5 col-b1"></view>
            </view>
          </view>
        </view>
        <!-- 报名时间活动时间范围选择 -->
        <uni-popup ref="startDatePopup" type="bottom" border-radius="20rpx 20rpx 0 0" backgroundColor="#fff">
          <view class="slanted-rectangle">
            <view class="fs-28 fw-600 mb-30">{{ timeType == 0 ? '报名时间' : '活动时间' }}</view>
            <DateSelector :mode="selectDateType" @onSubmit="onDateSelectorSubmit" :minDate="minDate" :maxDate="maxDate"
              :defaultStartDate="startDate" :defaultEndDate="endDate" />
          </view>
        </uni-popup>
        <!-- 活动地点 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen">
            <view class="fs-28 fw-600">活动地点</view>
            <view class="flex-dir-row ali-item-cen">
              <view @click="showAmapLocationPicker" v-if="activityLocation == ''" class="fs-26 mr-20 col-b1">选择活动地点
              </view>
                             <scroll-view v-else scroll-x class="fs-28 mr-20 text-element-1 whi-sp" style="width: 300rpx;">
                  <view class="location-display">
                    <view class="location-name">{{ activityLocation }}</view>
                    <view v-if="locationAddress && locationAddress !== activityLocation" class="location-address">{{ locationAddress }}</view>
                  </view>
                </scroll-view>
              <view @click="showAmapLocationPicker" class="iconfont ic-you fs-32 mt-5 col-b1"></view>
            </view>
          </view>
        </view>
      </view>
      <view class="heng"></view>
      <view class="ping-0-30">
        <!-- 活动是否付费 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen">
            <view class="fs-28 fw-600">付费活动</view>
            <!-- 多选框 -->
            <checkbox-group @change="activityIsPay = !activityIsPay">
              <checkbox color="#14cc60" :checked="activityIsPay" />
            </checkbox-group>
          </view>
        </view>
        <!-- 如果是付费活动，展示付费金额输入框 -->
        <view v-if="activityIsPay">
          <view class="bor-top-f3 ping-30-0">
            <view class="flex-dir-row flex-x-bet ali-item-cen">
              <view class="fs-28 fw-600">付费金额</view>
              <view class="text-ali-r">
                <input type="number" class="text-ali-r fs-28" v-model="activityPay" confirm-type="done"
                  placeholder-class="input-activity-number" placeholder="请输入付费金额，单位：分" />
                <view v-if="activityPay" class="fs-24 col-00ba31">{{ activityPay + '元' }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 活动人数 -->
        <view class="bor-top-f3 ping-30-0">
          <view class="flex-dir-row flex-x-bet ali-item-cen">
            <view class="fs-28 fw-600">活动人数</view>
            <input type="number" class="text-ali-r fs-28" v-model="activityPeople" confirm-type="done"
              placeholder-class="input-activity-number" placeholder="请输入活动人数" />
          </view>
        </view>
        <view>
          <view class="w-100 ping-30-0 bac-col-f activity-box bor-top-f3">
            <view class="w-100 flex-dir-row ali-item-cen flex-x-bet mb-30">
              <view class="fs-28 fw-600">社群二维码</view>
            </view>
            <uni-file-picker ref="files" v-model="groupCodeImg" return-type="array" limit="1" mode="grid"
              file-mediatype="image" :sizeType="['compressed']"
              :image-styles="{width: '160rpx', height: '160rpx',border:false,background:'#f7f7f7',borderRadius:'20rpx',lineHeight:'160rpx'}">
            </uni-file-picker>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部定位发布按钮 -->
    <view @click="publish" class="w-100 fixed-bottom bac-col-00b">
      <view class="w-100 bg-col-00b text-ali-c">
        <view class="fs-30 col-f fw-600">发布活动</view>
      </view>
    </view>
  </view>
</template>

<script>
  import DateSelector from '@/components/dengrq-datetime-picker/dateSelector/index.vue';
  import {
    getTagListApi
  } from '@/api/activity/activityTag.js';
  import {
    getActivityTypeApi
  } from '@/api/activity/activityType.js';
  import {
    getGoodsListApi
  } from '@/api/goods/goods.js';
  import {
    getActivityDetailForEditApi,
    addActivityDataApi,
    updateActivityDataApi
  } from '@/api/activity/activity.js';


  export default {
    components: {
      DateSelector
    },
    data() {
      return {
        // #ifdef MP-WEIXIN
        menuObject: uni.getMenuButtonBoundingClientRect(),
        // #endif
        // #ifndef MP-WEIXIN
        menuObject: 0,
        // #endif // 获取菜单按钮的坐标
        imgUrl: [], // 活动图片
        title: '', // 活动标题
        content: '<p style="color: #b1b1b1;font-size: 30rpx;">点击去填写活动详情</p>', // 活动详情
        activityTagList: [], // 活动标签列表
        searchTag: '', // 搜索标签
        selectedActivity: [], // 选择的标签
        activityType: '', // 活动分类
        activityTypeList: [], // 活动分类列表
        selectDateType: 4, // 选择报名时间范围的类型
        minDate: '', // 可选的最小日期,默认当前时间后一年
        maxDate: '', // 可选的最大日期,默认当前时间后一年
        startDate: new Date().toLocaleDateString(), // 选中的开始时间
        endDate: '', // 选中的结束时间
        timeType: 0, //选中的时间类型，报名0-活动1
        signUpSTime: '', // 报名开始时间
        signUpETime: '', // 报名结束时间
        activitySTime: '', // 活动开始时间
        activityETime: '', // 活动结束时间
        latitude: '', // 纬度
        longitude: '', // 经度
        activityLocation: '', // 活动地点
        locationName: '', // 位置名称
        locationAddress: '', // 位置地址
        activityPeople: '', // 活动人数
        activityIsPay: false, // 活动是否付费
        activityPay: '', // 付费金额
        groupCodeImg: [], // 社群二维码
        activityId: '', // 活动id
        activityData: [], // 活动数据
        dataLoaded: false, // 数据是否加载完成

        // 礼品相关
        giftList: [], // 礼品列表
        selectedGift: '', // 选中的礼品id
        selectedGiftName: '', // 选中的礼品名称
        tempSelectedGift: '', // 临时选中的礼品id
        tempSelectedGiftName: '', // 临时选中的礼品名称
        giftSearchKeyword: '', // 礼品搜索关键词
      }
    },
    computed: {
      // 计算筛选后的活动标签列表
      filteredActivityTagList() {
        if (!this.searchTag.trim()) {
          return this.activityTagList;
        }
        return this.activityTagList.filter(item => item.name.includes(this.searchTag));
      },

      // 计算筛选后的礼品列表
      filteredGiftList() {
        if (!this.giftSearchKeyword.trim()) {
          return this.giftList;
        }
        return this.giftList.filter(item =>
          item.name.toLowerCase().includes(this.giftSearchKeyword.toLowerCase())
        );
      }
    },
    mounted() {
      this.minDate = new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toLocaleDateString();
      this.maxDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toLocaleDateString();
    },
    onLoad(e) {
      if (e.id) {
        this.activityId = e.id;
        // 如果存在活动id则为修改，获取活动详情
        this.getActivityDetailForEdit();
      }
      // 获取活动标签列表
      this.getTagList();
      // 获取活动分类
      this.getActivityType();
      // 获取礼品列表
      this.getGiftList();

      // 监听全局位置选择事件（备用方案）
      uni.$on('locationSelected', this.handleLocationSelected);
    },

    onUnload() {
      // 移除全局事件监听
      uni.$off('locationSelected', this.handleLocationSelected);
    },

    onShow() {
      // 页面显示时检查是否有缓存的位置信息（兜底方案）
      try {
        const cachedLocation = uni.getStorageSync('selectedLocation');
        if (cachedLocation) {
          const location = JSON.parse(cachedLocation);
          console.log('从缓存获取位置信息:', location);
          this.handleLocationSelected(location);
          // 清除缓存
          uni.removeStorageSync('selectedLocation');
        }
      } catch (error) {
        console.error('读取缓存位置信息失败:', error);
      }
    },
    methods: {
      // 获取活动详情
      getActivityDetailForEdit() {
        getActivityDetailForEditApi(this.activityId).then((res) => {
          const activityData = res.data.data || res.data;
          this.activityData = activityData;
          this.imgUrl = activityData.images ? JSON.parse(activityData.images) : []; // 活动图片
          this.title = activityData.title; // 活动标题
          this.content = activityData.description; // 活动详情
          this.selectedActivity = activityData.tags ? JSON.parse(activityData.tags) : []; // 活动标签
          this.activityType = activityData.categoryId; // 活动分类
          this.signUpSTime = this.formatTimestamp(activityData.registrationStartTime); // 报名开始时间
          this.signUpETime = this.formatTimestamp(activityData.registrationEndTime); // 报名结束时间
          this.activitySTime = this.formatTimestamp(activityData.startTime); // 活动开始时间
          this.activityETime = this.formatTimestamp(activityData.endTime); // 活动结束时间
          this.latitude = activityData.latitude; // 纬度
          this.longitude = activityData.longitude; // 经度
          this.activityLocation = activityData.location; // 活动地点

          // 解析位置信息（如果有的话）
          this.locationAddress = activityData.address || '';

          // 处理isFree与activityIsPay的逻辑相反问题
          this.activityIsPay = activityData.isFree === 0; // isFree=0表示收费，activityIsPay=true表示付费
          this.activityPay = activityData.price; // 付费金额
          this.activityPeople = activityData.maxParticipants; // 活动人数

          // 设置礼品
          if (activityData.giftId) {
            this.selectedGift = activityData.giftId;

            // 如果已经加载了礼品列表，可以从中找到对应的礼品名称
            if (this.giftList.length > 0) {
              const gift = this.giftList.find(item => item.id === activityData.giftId);
              if (gift) {
                this.selectedGiftName = gift.goodsName;
              }
            } else {
              // 如果还没有加载礼品列表，可以在加载完毕后再设置名称
              this.getGiftDetail(activityData.giftId);
            }
          }

          // 判断活动是否在进行中，进行中的活动不能被编辑
          if (new Date(activityData.startTime).getTime() < Date.now() && new Date(activityData.endTime).getTime() >
            Date.now()) {
            this.$Toast('活动正在进行中，不能被编辑');
            setTimeout(() => this.$NavigateBack(), 1600)
            return;
          }
          // 判断活动是否已结束，已结束的活动不能被编辑
          if (new Date(activityData.endTime).getTime() < Date.now()) {
            this.$Toast('活动已结束，不能被编辑');
            setTimeout(() => this.$NavigateBack(), 1600)
            return;
          }
          // 如果是付费活动且报名已开启不能被编辑
          if (activityData.isFree === 0 && new Date(activityData.registrationStartTime).getTime() < Date.now()) {
            this.$Toast('付费活动报名已开启，不能被编辑');
            setTimeout(() => this.$NavigateBack(), 1600)
            return;
          }
          // 如果是管理端新增的活动，提示用户到管理端编辑
          if (!this.imgUrl || this.imgUrl.length === 0 || !this.imgUrl[0].uuid) {
            this.$Toast('该活动为管理端创建，请到管理端编辑');
            setTimeout(() => this.$NavigateBack(), 1600)
            return;
          }
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
        });
      },
      // 获取活动标签列表
      getTagList() {

        getTagListApi().then(res => {
          this.activityTagList = res.data.data;
          // this.dataLoaded = true;
        })
      },
      // 获取活动分类
      getActivityType() {
        getActivityTypeApi().then((res) => {
          this.activityTypeList = res.data.data;
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
        });
      },
      // 向用户获取授权并打开地图选择位置
      showActivityLocation() {
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => {
            uni.chooseLocation({
              success: (res) => {
                if (res.address) {
                  this.activityLocation = res.address + res.name;
                } else {
                  this.activityLocation = res.name;
                }
                this.latitude = res.latitude;
                this.longitude = res.longitude;
              },
              fail: (err) => {
                console.log(err)
              }
            })
          },
          fail: (err) => {
            console.log(err)
          }
        })
      },

      // 打开高德地图选择位置
      showAmapLocationPicker() {
        // 准备初始位置数据
        const initialLocation = {
          latitude: this.latitude || 0,
          longitude: this.longitude || 0,
          name: this.locationName || '',
          address: this.locationAddress || ''
        };

        // 构建参数（手动拼接，避免中文编码问题可自行 encodeURIComponent）
        const params = [
          `latitude=${encodeURIComponent(String(initialLocation.latitude))}`,
          `longitude=${encodeURIComponent(String(initialLocation.longitude))}`,
          `name=${encodeURIComponent(initialLocation.name)}`,
          `address=${encodeURIComponent(initialLocation.address)}`
        ].join('&');

        // 跳转到地图选择页面
        uni.navigateTo({
          url: `/pages/map/location-picker?${params}`,
          events: {
            locationSelected: (location) => {
              console.log('接收到位置选择结果:', location);
              this.handleLocationSelected(location);
            }
          },
          success: () => {
            console.log('成功跳转到地图选择页面');
          },
          fail: (err) => {
            console.error('跳转地图选择页面失败:', err);
            this.$Toast('打开地图失败，请重试');
          }
        });
      },

             // 处理位置选择结果
       handleLocationSelected(location) {
         console.log('处理位置选择结果:', location);
         
         // 更新位置信息
         this.latitude = location.latitude || 0;
         this.longitude = location.longitude || 0;
         this.locationName = location.name || '';
         this.locationAddress = location.address || '';
 
         // 设置活动地点字段（用于后台接口）
         if (location.address && location.name) {
           this.activityLocation = location.name;
         } else if (location.name) {
           this.activityLocation = location.name;
         } else if (location.address) {
           this.activityLocation = location.address;
         } else {
           this.activityLocation = '已选择位置';
         }
 
         // 显示成功提示
         this.$Toast('位置选择成功');
         console.log('位置信息已更新:', {
           latitude: this.latitude,
           longitude: this.longitude,
           locationName: this.locationName,
           locationAddress: this.locationAddress,
           activityLocation: this.activityLocation
         });
       },
      // 显示报名时间范围选择
      showStartDate(e) {
        this.timeType = e;
        this.$refs.startDatePopup.open();
      },
      // 确认报名时间范围
      onDateSelectorSubmit({
        startDate,
        endDate
      }) {
        if (this.timeType == 0) {
          this.signUpSTime = startDate;
          this.signUpETime = endDate;
        } else {
          this.activitySTime = startDate;
          this.activityETime = endDate;
        }
        this.$refs.startDatePopup.close();
      },
      // 选择标签
      activeActivity(index) {
        // 如果标签已存在则删除，不存在则添加
        if (this.selectedActivity.includes(index)) {
          this.selectedActivity = this.selectedActivity.filter(item => item !== index);
        } else {
          this.selectedActivity.push(index);
        }
      },
      // 清除活动标题
      clearTitle() {
        this.title = '';
      },
      // 显示活动分类选择
      showActivityType() {
        this.$refs.popup.open();
      },
      // 选择活动分类
      selectActivityType(item) {
        this.activityType = item;
        this.$refs.popup.close();
      },
      // 跳转
      naTov(url) {
        // 传递this.content富文本过去并且防止过长折叠
        // 默认的this.content不传递
        const content = this.content == '<p style="color: #b1b1b1;font-size: 30rpx;">点击去填写活动详情</p>' ? '' : this
          .content;
        uni.navigateTo({
          url: `${url}?data=${encodeURIComponent(content)}&source=notice`,
          events: {
            refreshData: (data) => {
              if (data.length > 7) {
                this.content = data;
              } else {
                this.content = '<p style="color: #b1b1b1;font-size: 30rpx;">点击去填写活动详情</p>'
              }
            }
          }
        })
      },
      // 获取单个礼品详情
      getGiftDetail(id) {
        this.$Route('get-public-data', true).getGoodsDetail(id).then(res => {
          if (res.data) {
            this.selectedGiftName = res.data.name;
          }
        }).catch(err => {
          console.error('获取礼品详情失败:', err);
        });
      },

      // 获取礼品列表
      getGiftList() {
        getGoodsListApi().then(res => {
          this.giftList = res.data.data;

          // 如果已经选择了礼品但还没有名称，从列表中找到对应的礼品名称
          if (this.selectedGift && !this.selectedGiftName) {
            const gift = this.giftList.find(item => item.id === this.selectedGift);
            if (gift) {
              this.selectedGiftName = gift.name;
            }
          }
        }).catch(err => {
          console.error('获取礼品列表失败:', err);
          let {
            code,
            msg
          } = this.$parseError(err);
          this.$Toast(msg);
        });
      },

      // 显示礼品选择弹窗
      showGiftSelector() {
        // 记录当前选择的礼品，以便取消时恢复
        this.tempSelectedGift = this.selectedGift;
        this.tempSelectedGiftName = this.selectedGiftName;
        this.$refs.giftPopup.open();
      },

      // 选择礼品
      selectGift(id, name) {
        this.tempSelectedGift = id;
        this.tempSelectedGiftName = name;
      },

      // 确认礼品选择
      confirmGiftSelection() {
        this.selectedGift = this.tempSelectedGift;
        this.selectedGiftName = this.tempSelectedGiftName;
        this.$refs.giftPopup.close();
      },
      // 发布/编辑活动
      publish() {
        this.$debounce(async () => {
          // 震动
          uni.vibrateShort();
          // 先判断必填所有参数是否填写完成
          if (this.imgUrl.length == 0) {
            this.$Toast('请上传活动图片');
            return;
          }
          if (this.title.trim() == '') {
            this.$Toast('请填写活动标题');
            return;
          }
          if (this.content == '<p style="color: #b1b1b1;font-size: 30rpx;">点击去填写活动详情</p>' || this
            .content
            .trim() ==
            '') {
            this.$Toast('请填写活动详情');
            return;
          }
          // 如果付费活动，付费金额不能为空
          if (this.activityIsPay && (!this.isInteger(this.activityPay) || Number(this.activityPay) <=
              0)) {
            this.$Toast('请检查活动付费金额');
            return;
          }
          // 分类不能为空
          if (this.activityType.trim() == '') {
            this.$Toast('请选择活动分类');
            return;
          }
          // 如果活动地点为空
          if (this.activityLocation.trim() == '' || this.latitude == '' || this.longitude == '') {
            this.$Toast('请选择活动地点');
            return;
          }
          // 检查报名时间和活动时间
          if (this.signUpSTime.trim() == '' || this.signUpETime.trim() == '' || this.activitySTime
            .trim() == '' ||
            this.activityETime.trim() == '') {
            this.$Toast('请选择报名时间和活动时间');
            return;
          }
          // 转换报名时间和活动时间为时间戳
          const signUpSTime = new Date(this.signUpSTime).getTime(); // 报名开始时间
          const signUpETime = new Date(this.signUpETime).getTime(); // 报名结束时间
          const activitySTime = new Date(this.activitySTime).getTime(); // 活动开始时间
          const activityETime = new Date(this.activityETime).getTime(); // 活动结束时间
          // 如果报名开始时间大于报名结束时间，则提示用户
          if (signUpSTime > signUpETime) {
            this.$Toast('报名开始时间不能大于报名结束时间');
            return;
          }
          // 如果活动开始时间大于活动结束时间，则提示用户
          if (activitySTime > activityETime) {
            this.$Toast('活动开始时间不能大于活动结束时间');
            return;
          }
          // 如果活动开始时间小于报名结束时间，则提示用户
          if (activitySTime < signUpETime) {
            this.$Toast('活动开始时间不能小于报名结束时间');
            return;
          }

          if (!this.isInteger(this.activityPeople) || Number(this.activityPeople) <= 0) {
            this.$Toast('请检查活动人数');
            return;
          }
          if (this.activityId) {
            await this.editActivity();
          } else {
            await this.publishActivity();
          }
        }, 500, true, "publish")
      },
      // 编辑活动
      async editActivity() {
        // 开始编辑活动
        await updateActivityDataApi({
          id: this.activityId, // 活动id
          title: this.title, // 活动标题
          description: this.content, // 活动详情
          images: JSON.stringify(this.imgUrl), // 活动图片
          tags: JSON.stringify(this.selectedActivity), // 活动标签
          categoryId: this.activityType, // 活动分类
          registrationStartTime: this.signUpSTime, // 报名开始时间
          registrationEndTime: this.signUpETime, // 报名结束时间
          startTime: this.activitySTime, // 活动开始时间
          endTime: this.activityETime, // 活动结束时间
          latitude: this.latitude, // 纬度
          longitude: this.longitude, // 经度
          location: this.activityLocation, // 活动地点
          address: this.locationAddress, // 详细地址
          maxParticipants: this.activityPeople, // 活动人数
          isFree: this.activityIsPay ? 0 : 1, // 是否免费（逻辑相反）
          price: this.activityPay, // 付费金额
          giftId: this.selectedGift, // 活动礼品
        }).then((res) => {
          this.$Toast(res.msg);
          this.getOpenerEventChannel().emit('refreshData', '')
          setTimeout(() => this.$NavigateBack(), 1000)
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
          setTimeout(() => {
            if (code === 401) {
              this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
            } else if (code === 400) {
              this.$NavigateTo('/qmy_user/user/userPersonal'); // 跳转到个人信息页面
            } else if (code == 500) {
              this.$NavigateBack()
            }
          }, 1000);
        })
      },
      // 发布活动
      async publishActivity() {
        // 开始发布活动
        await addActivityDataApi({
          title: this.title, // 活动标题
          description: this.content, // 活动详情
          images: JSON.stringify(this.imgUrl), // 活动图片
          tags: JSON.stringify(this.selectedActivity), // 活动标签
          categoryId: this.activityType, // 活动分类
          registrationStartTime: this.signUpSTime, // 报名开始时间
          registrationEndTime: this.signUpETime, // 报名结束时间
          startTime: this.activitySTime, // 活动开始时间
          endTime: this.activityETime, // 活动结束时间
          latitude: this.latitude, // 纬度
          longitude: this.longitude, // 经度
          location: this.activityLocation, // 活动地点
          address: this.locationAddress, // 详细地址
          maxParticipants: this.activityPeople, // 活动人数
          isFree: this.activityIsPay ? 0 : 1, // 是否免费（逻辑相反）
          price: this.activityPay, // 付费金额
          giftId: this.selectedGift, // 活动礼品
        }).then((res) => {
          this.$Toast(res.msg);
          setTimeout(() => {
            this.$NavigateTo('/pages/index/index');
          }, 1000);
        }).catch((err) => {
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
          setTimeout(() => {
            if (code === 401) {
              this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
            } else if (code === 400) {
              this.$NavigateTo('/qmy_user/user/userPersonal'); // 跳转到个人信息页面
            } else if (code == 500) {
              this.$NavigateBack()
            }
          }, 1000);
        })
      },
      // 检查整数
      isInteger(str) {
        return /^[0-9]+$/.test(str);
      },
      formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        const Y = date.getFullYear();
        const M = String(date.getMonth() + 1).padStart(2, '0'); // 月份补0
        const D = String(date.getDate()).padStart(2, '0'); // 日期补0
        const h = String(date.getHours()).padStart(2, '0'); // 小时补0
        const m = String(date.getMinutes()).padStart(2, '0'); // 分钟补0
        const s = String(date.getSeconds()).padStart(2, '0'); // 秒钟补0
        return `${Y}-${M}-${D} ${h}:${m}:${s}`;
      }
    }
  }
</script>

<style lang="scss">
  .upload-image {
    width: 160rpx;
    height: 160rpx;

    .upload-image-item {
      line-height: 160rpx;
    }
  }

  .textarea-box {
    height: 300rpx;
  }

  .input-box {
    width: 100%;
    height: 90rpx;
    border-bottom: 1rpx solid #f3f3f3;
  }

  .input-placeholder {
    font-size: 30rpx;
    color: #b1b1b1;
    font-weight: normal;
  }

  .textarea-placeholder {
    font-size: 28rpx;
    color: #b1b1b1;
    font-weight: normal;
  }

  .mp-html-box {
    height: 300rpx;
  }

  .activity-item {
    border-radius: 10rpx;
    background-color: #f7f7f7;
  }

  .slanted-rectangle {
    width: 100%;
    background-color: white;
    border-top-left-radius: 40rpx;
    border-top-right-radius: 40rpx;
    padding: 0rpx 30rpx;
    padding-bottom: 30rpx;
    min-height: 400rpx;
  }

  .slanted-rectangle::before {
    content: '';
    position: absolute;
    top: -60rpx;
    z-index: -1;
    left: 0;
    width: 100%;
    height: 50%;
    background-color: white;
    transform: skewY(3deg);
    border-radius: 40rpx 40rpx 0 0;
  }

  .activity-type-item {
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 10rpx;
    width: 22%;
    text-align: center;
    margin-bottom: 20rpx;
  }

  .input-activity-number {
    font-size: 26rpx;
    color: #b1b1b1;
    font-weight: normal;
    text-align: right;
    width: 300rpx;
  }

  .fixed-bottom {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding-top: 30rpx;
    padding-bottom: 30rpx !important;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
    z-index: 9999;
    transition: background-color 0.2s ease;
  }

  .fixed-bottom:active {
    background-color: #11b051 !important;
    /* 点击时背景颜色变化 */
  }

  /* 添加活动礼品选择相关样式 */
  .gift-selector {
    display: flex;
    align-items: center;
    flex-direction: row;
  }

  .gift-search {
    width: 100%;

    .search-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #f7f7f7;
      border-radius: 200rpx;
      padding: 0 24rpx;
      height: 65rpx;

      .iconfont {
        margin-right: 10rpx;
      }

      .search-placeholder {
        font-size: 28rpx
      }

      input {
        flex: 1;
        height: 60rpx;
        font-size: 28rpx
      }
    }
  }

  .gift-list {
    .empty-gift {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
    }

    .gift-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f3f3f3;

      &:last-child {
        border-bottom: none;
      }

      .gift-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
        background-color: #f7f7f7;
      }

      .gift-info {
        flex: 1;

        .gift-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .gift-price {
          font-size: 26rpx;
          color: #ff4d4f;
        }
      }

      .gift-select {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 20rpx;

        &.selected {
          font-size: 42rpx;
          border: none !important;
          color: #14cc60;
        }
      }
    }
  }

  .gift-popup-footer {
    display: flex;
    margin-top: 30rpx;

    .cancel-btn,
    .confirm-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 10rpx;
      font-size: 28rpx;
    }

    .cancel-btn {
      background-color: #f7f7f7;
      color: #666;
      margin-right: 20rpx;
    }

    .confirm-btn {
      background-color: #14cc60;
      color: #fff;
    }
  }

  /* 位置显示样式 */
  .location-display {
    text-align: right;

    .location-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 5rpx;
    }

    .location-address {
      font-size: 24rpx;
      color: #999;
      line-height: 1.2;
    }
  }
</style>